/**
 * 患者信息栏的公共组件，搜索病案号、住院号、身份证号可以识别患者信息
 */
import { Button, Form } from 'antd';
import React, { useState, useRef, useImperativeHandle, forwardRef } from 'react';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { FormInstance } from 'antd';
import { getPatientHospitalizationInfo, getPatientList, getDischargeStatus } from '@/services/order/api';
import ProTable from '@ant-design/pro-table';
import { useModel } from 'umi';
import { isNull, showMsg, MsgType, searchKey } from '@/utils/utils';
import moment from 'moment';
import './index.less';


interface MyProps {
  changePatient?: Function; // 更换患者回调
  onChoice?: Function; // 选择住院号回调
  showMore?: Boolean; // 是否显示多条住院号
  fromTo?: string; // 来自哪个页面的
  label?: string; // 输入框label
  placeholder?: string; // 输入框placeholder
}
const GoodName: React.FC<MyProps> = forwardRef((props, ref) => {
  const { changePatient, onChoice, showMore, fromTo, label, placeholder } = props;
  // 患者信息
  const [patientInfo, setPatientInfo] = useState<ORDERAPI.PatientHospitalInfo>({});
  const formRef = useRef<FormInstance>();
  // 住院记录列表，一个患者可能有多条住院记录
  const [caseList, setCaseList] = useState([]);
  // 当前选择的住院记录
  const [selectedRow, setSelectedRow] = useState<STOCKGOODSAPI.GoodsItem>([]);
  const { initialState } = useModel('@@initialState');

  const columns = [
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      search: false,
      width: 60,
    },
    {
      title: '性别',
      dataIndex: 'patient_sex_name',
      search: false,
      width: 40,
    },
    {
      title: '身份证',
      dataIndex: 'identity_no',
      search: false,
      width: 140,
    },
    {
      title: '就诊卡',
      dataIndex: 'ic_card_no',
      search: false,
      width: 100,
    },
  ]

  const columns1 = [
    {
      title: '住院号',
      dataIndex: 'visit_no',
      search: false,
      width: 60,
    },
    {
      title: '住院记录',
      dataIndex: 'is_in',
      search: false,
      width: 100,
      render: (val, record) => {
        if (val === 'Y') {
          return '住院中'
        }
        const cy = (record.discharge_time || '').substring(0, 8);
        return `${isNull(cy) ? '已' : moment(cy).format('YYYY-MM-DD')}出院`
      }
    },
  ]

  // 根据身份证查询患者信息，传了key代表要查询住院信息（传给接口的具体属性名）
  const fetchPatientBySfz = async (data: { identity_no?: string; ic_card_no: string}, key?: string) => {
    try {
      setCaseList([])
      const list = await getPatientList(data);

      if(!list.length) {
        showMsg('未找到患者信息!', MsgType.ERROR);
        return;
      }
      // 一次性订单
      if (fromTo === 'onceOrder') {
        // 只有一条记录时，默认选中第一条记录
        if (!isNull(data.identity_no) || list.length === 1) {
          onChoice?.(list[0]);
          setPatientInfo(list[0]);
        } else { // 有多条记录，则显示表格供用户选择
          setCaseList(list);
        }
      } else { // 其他页面入口 调用患者住院号查询接口获取更多信息
        await fetchPatientByCaseNo({ [key]: list[0].case_no });
      }
      // if (type === 'zy') {
        // await fetchPatientByCaseNo(res.case_no);
      // }
    } catch (error) {
      console.log('error', error)
      showMsg(error?.data?.errmsg);
    }
  }

  // 判断是否出院办结
  const checkOrder = async(info) => {
    const data = await getDischargeStatus({
      patient_id: info.patient_id,
      admission_num: info.visit_no
    });

    if (['W'].includes(data.manager_status)) {
      showMsg('存在处理中的出院办结信息', MsgType.INFO);
      if (fromTo === 'onceOrder') {
        return;
      }
    } else if (['F'].includes(data.manager_status)) {
      showMsg('患者已办理出院，无法创建订单', MsgType.INFO);
      if (fromTo === 'onceOrder') {
        return;
      }
    }

    setPatientInfo(info);
    onChoice?.(info, data);
    formRef.current?.setFieldsValue({
      patient_name: info?.patient_name,
      address: `${info.ward_address}${info.bed_no}床位`
    });
  }

  // 患者住院号查询
  const fetchPatientByCaseNo = async (params: string) => {
    try {
      const data: ORDERAPI.PatientHospitalInfo[] = await getPatientHospitalizationInfo({ ...params, flag: fromTo === 'onceOrder' || fromTo === 'planOrder' ? 'Y' : '' });
      let info: ORDERAPI.PatientHospitalInfo = {};

      if (Array.isArray(data) && data.length > 0) {
        if (showMore && data.length > 1) {
          showMsg('检测到有多条住院记录，请选择', 'info');
          setCaseList(data);
        } else {
          info = data[0];
          // 计划订单 或 一次性订单，需要判断是否出院办结，如无办理则可继续创建/操作订单
          if (fromTo === 'planOrder' || fromTo === 'onceOrder') {
            checkOrder(info);
          } else {
            setPatientInfo(info);
            onChoice?.(info, data);
            formRef.current?.setFieldsValue({
              patient_name: info?.patient_name,
              address: `${info.ward_address}${info.bed_no}床位`
            });
          }
        }
      } else {
        showMsg('未找到患者信息', MsgType.INFO);
        formRef.current?.setFieldsValue({
          patient_name: null,
          address: null
        });
      }
    } catch (error) {
      console.log('error', error);
      showMsg(error?.data?.errmsg);
    }
  }

  // 选择住院号
  const choiceZyh = () => {
    console.log('selectedRow', selectedRow);
    setPatientInfo(selectedRow);
    onChoice?.(selectedRow);
    formRef.current?.setFieldsValue({
      patient_name: selectedRow?.patient_name,
      address: `${selectedRow.ward_address}${selectedRow.bed_no}床位`
    });
    setCaseList([]);
    document.getElementById('root').scrollTo(0, 0)
  }

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    clear: () => {
      setPatientInfo({});
      formRef.current?.resetFields();
    },
    // 更新患者信息
    update: (e) => {
      setPatientInfo(e);
    },
    // 搜索患者信息
    fetch: async(e) => {
      formRef.current?.setFieldsValue({ input_no: e })
      await fetchPatientByCaseNo({ [searchKey(e, initialState?.canAll, fromTo)]: e });
    }
  }))

  // const tableWidth = isNull(document.getElementsByClassName('patient-form')[0]) ? 280 : document.getElementsByClassName('patient-form')[0].getElementsByClassName('ant-row')[0].clientWidth;
  // const tableWidth = 200;
  return (
    <div className='patient-form'>
      <ProForm
        className="order-pro-form service-record"
        style={{ padding: '0px 20px' }}
        submitter={
          {
            searchConfig: {
              submitText: isNull(patientInfo.patient_id) ? '查询' : '更换患者'
            },
            submitButtonProps: {
              style: {
                // display: type === OptType.ADD ? 'block' : 'none'
              },
              // disabled: type === OptType.EDIT
            },
            resetButtonProps: {
              style: {
                display: 'none'
              }
            },
          }
          //  : false
      }
      formRef={formRef}
      onFinish={async (values) => {
        console.log('onFinish', values, patientInfo);
        if (!isNull(patientInfo.patient_id)) {
          // 更换患者
          if (changePatient) {
            changePatient?.();
          } else {
            formRef.current?.setFieldsValue({ input_no: null });
            setPatientInfo({});
          }
          return;
        }
        const { input_no, patient_name, tele_phone } = values;
        if (fromTo === 'onceOrder' && isNull(input_no) && isNull(patient_name) && isNull(tele_phone)) {
          showMsg('请输入身份证/病案号或患者姓名或手机号', MsgType.INFO);
          return;
        } else if (fromTo !== 'onceOrder' && isNull(input_no)) {
          showMsg('请输入身份证/病案号', MsgType.INFO);
          return;
        }
        console.log('identity_no', input_no);
        console.log('patient_name111', patient_name)
        if (!isNull(input_no)) {
          // 病案号
          // if ((input_no.length > 4 && input_no.length < 15 && Number.isFinite(parseFloat(input_no))) || input_no.indexOf('IMP') > -1) {
          //   await fetchPatientByCaseNo({[searchKey(input_no, initialState?.canAll, fromTo)]: input_no});
          // } else
          if (input_no.length === 15 || input_no.length === 18) { // 身份证
            await fetchPatientBySfz({ identity_no: input_no }, searchKey(input_no, initialState?.canAll));
          } else if (input_no.length > 10 && input_no.length < 15 && fromTo === 'onceOrder') { // 就诊卡 && 一次性订单页面用到
            await fetchPatientBySfz({ ic_card_no: input_no }, searchKey(input_no, initialState?.canAll));
          } else if (input_no.includes('R')) { // 住院号
            await fetchPatientByCaseNo({ [searchKey(input_no, initialState?.canAll, fromTo)]: input_no });
          } else {
            // showMsg('身份证或病案号输入有误', MsgType.INFO);
            await fetchPatientByCaseNo({[searchKey(input_no, initialState?.canAll, fromTo)]: input_no});
          }
        } else if (!isNull(patient_name) || !isNull(tele_phone)) {
          // console.log('patient_name222', patient_name)
          await fetchPatientBySfz({ patient_name, tele_phone });
        }

      }}
      layout='inline'>
        <ProForm.Group>
          {
            fromTo === 'rent' &&
            <Form.Item label="病区">
              <span>{initialState?.currentUser?.ward_name}</span>
            </Form.Item>
          }
          {
            isNull(patientInfo.patient_id) ? <ProFormText
              // disabled={type === OptType.EDIT}
              label={label || "身份证/病案号"}
              name="input_no"
              placeholder={placeholder || "输入身份证号/病案号/住院号"}
              width={200}
              fieldProps={{
                onPressEnter: (e) => {
                  e.preventDefault();
                  formRef.current?.submit()
                },
                onChange: (e) => {
                  const val = e.target.value;
                  // 住院记录有值的情况下，如果更改了输入框的信息，则清空住院记录
                  if (!isNull(caseList) && val !== caseList[0].case_no) {
                    setCaseList([]);
                  }
                }
              }}
            /> : ((!isNull(patientInfo.identity_no) || !isNull(patientInfo.case_no)) && (fromTo !== 'onceOrder' || (fromTo === 'onceOrder' && isNull(formRef.current?.getFieldValue('patient_name'))))) && <Form.Item label="身份证/病案号">
              <span>{patientInfo.identity_no}{!isNull(patientInfo.identity_no) && !isNull(patientInfo.case_no) ? ' / ' : ''}{patientInfo.case_no}</span>
            </Form.Item>
          }
          {
            // 一次性订单可根据患者姓名查询
            fromTo === 'onceOrder' && (
            isNull(patientInfo.patient_id) ? <ProFormText
              // disabled={type === OptType.EDIT}
              label="患者姓名"
              name="patient_name"
              placeholder="输入患者姓名"
              width={200}
              fieldProps={{
                onPressEnter: (e) => {
                  e.preventDefault();
                  formRef.current?.submit()
                },
                onChange: (e) => {
                  const val = e.target.value;
                  if (!isNull(caseList) && val !== caseList[0].case_no) {
                    setCaseList([]);
                  }
                }
              }}
            /> : ((!isNull(patientInfo.identity_no) || !isNull(patientInfo.case_no)) && !isNull(formRef.current?.getFieldValue('patient_name'))) && <Form.Item label="身份证/就诊卡">
              <span>{patientInfo.identity_no}{!isNull(patientInfo.identity_no) && !isNull(patientInfo.ic_card_no) ? ' / ' : ''}{patientInfo.ic_card_no}</span>
            </Form.Item>)
          }
          {
            // 展示已查询出的患者信息
            !isNull(patientInfo.patient_id) &&
            <>
              <Form.Item label="患者姓名">
                <span>{patientInfo.patient_name}</span>
              </Form.Item>
              {!isNull(patientInfo.patient_sex_name) && <Form.Item label="性别"><span>{patientInfo.patient_sex_name || '-'}</span></Form.Item>}
              {
                !isNull(patientInfo.visit_no) && <Form.Item label="住院号"><span>{patientInfo.visit_no}</span></Form.Item>
              }
              {
                !isNull(patientInfo.dept_name) && <Form.Item label="归属科室"><span>{patientInfo.dept_name}</span></Form.Item>
              }
              {
                !isNull(patientInfo.patient_dept_name) && <Form.Item label="所属科室"><span>{patientInfo.patient_dept_name}</span></Form.Item>
              }
              {
                !isNull(patientInfo.bed_no) && <Form.Item label="床位号"><span>{patientInfo.bed_no}</span></Form.Item>
              }
            </>
          }
          {
            // 一次性订单可根据患者姓名查询
            fromTo === 'onceOrder' && (
            isNull(patientInfo.patient_id) ? <ProFormText
              // disabled={type === OptType.EDIT}
              label="手机号"
              name="tele_phone"
              placeholder="输入手机号"
              width={200}
              rules={[{ min: 11, message: '请输入完整手机号查询' }]}
              fieldProps={{
                onPressEnter: (e) => {
                  e.preventDefault();
                  formRef.current?.submit()
                },
                onChange: (e) => {
                  const val = e.target.value;
                  if (!isNull(caseList) && val !== caseList[0].case_no) {
                    setCaseList([]);
                  }
                }
              }}
            /> : <Form.Item label="手机号">
              <span>{patientInfo.mobile}</span>
            </Form.Item>)
          }
        </ProForm.Group>
      </ProForm>
      {
        // 如有多条住院记录，则显示该表格，供操作人员选择对应住院记录
        !isNull(caseList) &&
        <div style={{ width: fromTo === 'onceOrder' ? 380 : 270, marginLeft: fromTo === 'onceOrder' ? 328 : 20, position: 'absolute', zIndex: 1 }}>
          <ProTable
            rowKey={fromTo === 'onceOrder' ? 'ic_card_no' : 'visit_no'}
            // actionRef={actionRef}
            bordered
            className="worker-pro-table"
            formRef={formRef}
            manualRequest={true}
            rowSelection={{
              type: 'radio',
              columnWidth: 30,
              onChange: (selectedKeys, selectedRows) => {
                const row = selectedRows[0];
                setSelectedRow(row);
              }
            }}
            scroll={{ y: caseList.length > 15 ? 390 : null }}
            dataSource={caseList}
            search={false}
            options={false}
            toolBarRender={false}
            columns={fromTo === 'onceOrder' ? columns : columns1}
            pagination={false}
            footer={() => <div style={{ textAlign: 'right' }}><Button type='primary' onClick={choiceZyh}>确定</Button></div>}
          />
        </div>
      }
    </div>
  );
});

export default GoodName;
